package com.jumi.microservice.controller;

import com.jumi.microservice.common.base.BaseController;
import com.jumi.microservice.common.base.dto.BasePageResponse;
import com.jumi.microservice.common.base.dto.ResponseResult;
import com.jumi.microservice.common.constant.CloneDirection;
import com.jumi.microservice.common.constant.ImageResizeEnum;
import com.jumi.microservice.common.redis.RedisCache;
import com.jumi.microservice.common.utils.DateProvider;
import com.jumi.microservice.common.utils.ImageResizeUtil;
import com.jumi.microservice.common.utils.ObjectUtils;
import com.jumi.microservice.common.utils.ResultGenerator;
import com.jumi.microservice.constant.*;
import com.jumi.microservice.domain.*;
import com.jumi.microservice.dto.comment.dto.CommentApiOneResponse;
import com.jumi.microservice.dto.constant.ActivityTypeEnum;
import com.jumi.microservice.dto.reponse.GoodsActivityTypeResponse;
import com.jumi.microservice.dto.reponse.JmUserReponse;
import com.jumi.microservice.enums.Level;
import com.jumi.microservice.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 商品详情管理controller组件
 *
 * @author Administrator
 */
@RestController
@RequestMapping("/commodity/goodsDetail")
@RefreshScope
@Api(tags = "C端商品详情相关接口")
public class GoodsDetailController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(GoodsDetailController.class);

    /**
     * 商品spu管理service组件
     */
    @Autowired
    private GoodsService goodsService;

    /**
     * 商品sku管理service组件
     */
    @Autowired
    private GoodsSkuService goodsSkuService;

    /**
     * 商品详情管理service组件
     */
    @Autowired
    private GoodsDetailService goodsDetailService;

    /**
     * 库存管理service组件
     */
    @DubboReference
    private GoodsInventoryApi goodsInventoryApi;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 热门搜索标签
     */
    @Value("${goods.hotSearch.label}")
    private String goodsHotSearchLabel;

    /**
     * 会员管理service组件
     */
    @DubboReference
    private IMemberService memberService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 足迹管理service组件
     */
    @Autowired
    private GoodsFootprintService goodsFootprintService;

    /**
     * 商品活动管理service组件
     */
    @DubboReference
    private GorderActivityApi gorderActivityServiceClient;

    /**
     * 商品收藏管理service组件
     */
    @Autowired
    private GoodsFavoritesService goodsFavoritesService;

    /**
     * 商品评论管理service组件
     */
    @DubboReference
    private ICommentService commentService;

    /**
     * 商品搜索
     *
     * @param goodsSearchQuery 商品查询条件
     * @return 商品VO值对象集合
     */
    @ApiOperation(value = "C端商品搜索", notes = "C端商品搜索")
    @GetMapping("/search")
    public BasePageResponse<List<GoodsSearchVO>> searchGoodsByPage(GoodsSearchQuery goodsSearchQuery) {
        List<GoodsVO> goods = convertGoodsDtoList2VoList(goodsService.searchGoodsByPage(goodsSearchQuery, true));

        List<GoodsSearchVO> goodsSearchs = new ArrayList<>(goods.size());
        if (goods.size() > NumberConstant.NUMBER_ZERO.intValue()) {
            List<Long> goodsSpuIds = new ArrayList<>();
            for (GoodsVO goodsVo : goods) {
                goodsSpuIds.add(goodsVo.getId());

                GoodsSearchVO goodsSearch = new GoodsSearchVO();
                goodsSearch.setSpuId(goodsVo.getId());
                goodsSearch.setGoodsName(goodsVo.getGoodsName());
                goodsSearch.setGoodsImage(ImageResizeUtil.imageResize(goodsVo.getGoodsImage(), ImageResizeEnum.EXTRA_LARGE));

                goodsSearch.setGoodsDescription(goodsVo.getGoodsDescription());
                goodsSearch.setGoodsPrice(goodsVo.getGoodsPrice());
                goodsSearch.setGoodsMarketprice(goodsVo.getGoodsMarketprice());

                goodsSearchs.add(goodsSearch);
            }

            List<Long> goodsSkuIds = goodsService.getSkuIdListBySpuIds(goodsSpuIds);

            logger.info("commodity goods sku ids:{}", goodsSkuIds);
            Map<Long, List<GoodsSpuInventoryDTO>> spuInventoryMap = new HashMap<>(goods.size());
            if (goodsSkuIds.size() > NumberConstant.NUMBER_ZERO.intValue()) {
                //调用库存服务查询库存
                List<GoodsSpuInventoryDTO> goodsSpuInventories = goodsInventoryApi.goodsInventoryBySkuIds(goodsSkuIds);

                for (GoodsSpuInventoryDTO goodsSpuInventory : goodsSpuInventories) {
                    if (!spuInventoryMap.containsKey(goodsSpuInventory.getSpuId())) {
                        List<GoodsSpuInventoryDTO> goodsSpuInventoryDTOList = new ArrayList<>();
                        goodsSpuInventoryDTOList.add(goodsSpuInventory);
                        spuInventoryMap.put(goodsSpuInventory.getSpuId(), goodsSpuInventoryDTOList);
                    } else {
                        spuInventoryMap.get(goodsSpuInventory.getSpuId()).add(goodsSpuInventory);
                    }
                }
            }

            // 判断是否开启虚拟销量
            int enableVirtualNum = redisCache.getCacheObject(GoodsKeyConstant.GOODS_VIRTUALNUM_KEY);

            for (GoodsSearchVO goodsVo : goodsSearchs) {
                if (spuInventoryMap.containsKey(goodsVo.getSpuId())) {
                    List<GoodsSpuInventoryDTO> goodsSpuInventoryDtoList = spuInventoryMap.get(goodsVo.getSpuId());
                    Integer storage = NumberConstant.NUMBER_ZERO.intValue();
                    Integer saleStorage = NumberConstant.NUMBER_ZERO.intValue();
                    for (GoodsSpuInventoryDTO goodsSpuInventory : goodsSpuInventoryDtoList) {
                        if (goodsSpuInventory.getSaledStorage() != null) {
                            storage += goodsSpuInventory.getSaledStorage();
                        }
                        if (goodsSpuInventory.getStockQuantity() != null) {
                            saleStorage += goodsSpuInventory.getStockQuantity() + goodsSpuInventory.getPreStorage();
                        }
                    }

                    if (enableVirtualNum == NumberConstant.NUMBER_ONE.intValue()) {
                        Integer virtualNum = goodsSkuService.countVirtualNumBySpuId(goodsVo.getSpuId());
                        if (virtualNum != null) {
                            storage += virtualNum;
                        }
                    }

                    goodsVo.setSaledStorage(storage);
                    goodsVo.setSaleStorage(saleStorage);
                } else {
                    goodsVo.setSaledStorage(NumberConstant.NUMBER_ZERO.intValue());
                    goodsVo.setSaleStorage(NumberConstant.NUMBER_ZERO.intValue());
                }

                if (redisCache.hasObjectByKey(GoodsKeyConstant.GOODS_KEY + goodsVo.getSpuId())) {
                    goodsVo.setGoodsViews(redisCache.getCacheObject(GoodsKeyConstant.GOODS_KEY + goodsVo.getSpuId()));
                } else {
                    goodsVo.setGoodsViews(NumberConstant.NUMBER_ZERO.intValue());
                }
            }

            //按价格排序
            if (StringUtils.isNotEmpty(goodsSearchQuery.getOrderByColumn())
                    && OrderColumn.PRICE.equals(goodsSearchQuery.getOrderByColumn())) {
                if (StringUtils.isNotEmpty(goodsSearchQuery.getIsAsc())) {
                    String sortType = goodsSearchQuery.getIsAsc().toLowerCase();
                    if (sortType.equals(SortType.DESC)) {
                        Collections.sort(goodsSearchs, new Comparator<GoodsSearchVO>() {
                            @Override
                            public int compare(GoodsSearchVO o1, GoodsSearchVO o2) {
                                return -(o1.getGoodsPrice().compareTo(o2.getGoodsPrice()));
                            }
                        });

                    } else if (sortType.equals(SortType.ASC)) {
                        Collections.sort(goodsSearchs, new Comparator<GoodsSearchVO>() {
                            @Override
                            public int compare(GoodsSearchVO o1, GoodsSearchVO o2) {
                                return o1.getGoodsPrice().compareTo(o2.getGoodsPrice());
                            }
                        });
                    }
                }
            }

            //按销量排序
            if (StringUtils.isNotEmpty(goodsSearchQuery.getOrderByColumn())
                    && OrderColumn.SALED.equals(goodsSearchQuery.getOrderByColumn())) {
                if (StringUtils.isNotEmpty(goodsSearchQuery.getIsAsc())) {
                    String sortType = goodsSearchQuery.getIsAsc().toLowerCase();
                    if (sortType.equals(SortType.DESC)) {
                        goodsSearchs.sort((x, y) -> -Integer.compare(x.getSaledStorage(), y.getSaledStorage()));
                    } else if (sortType.equals(SortType.ASC)) {
                        goodsSearchs.sort((x, y) -> Integer.compare(x.getSaledStorage(), y.getSaledStorage()));
                    }
                }
            }

            //按浏览量排序
            if (StringUtils.isNotEmpty(goodsSearchQuery.getOrderByColumn())
                    && OrderColumn.VIEW.equals(goodsSearchQuery.getOrderByColumn())) {
                if (StringUtils.isNotEmpty(goodsSearchQuery.getIsAsc())) {
                    String sortType = goodsSearchQuery.getIsAsc();
                    if (sortType.equals(SortType.DESC)) {
                        goodsSearchs.sort((x, y) -> -Integer.compare(x.getGoodsViews(), y.getGoodsViews()));
                    } else if (sortType.equals(SortType.ASC)) {
                        goodsSearchs.sort((x, y) -> Integer.compare(x.getGoodsViews(), y.getGoodsViews()));
                    }
                }
            }
        }

        int rowCount = goodsSearchs.size();
        int pageCount;
        if (rowCount % goodsSearchQuery.getPageSize() == NumberConstant.NUMBER_ZERO.intValue()) {
            pageCount = rowCount / goodsSearchQuery.getPageSize();
        } else {
            pageCount = rowCount / goodsSearchQuery.getPageSize() + NumberConstant.NUMBER_ONE.intValue();
        }

        return ResultGenerator.genSuccessResultPage(
                goodsSearchs.stream()
                        .skip(goodsSearchQuery.getPageSize() * (goodsSearchQuery.getPageNum() - NumberConstant.NUMBER_ONE.intValue()))
                        .limit(goodsSearchQuery.getPageSize()).collect(Collectors.toList())
                , Long.valueOf(goodsSearchs.size()), Long.valueOf(pageCount));
    }

    /**
     * 根据商品spu id查询商品详情
     *
     * @param goodsId 商品id
     * @return 商品详情
     */
    @ApiOperation(value = "C端商品spu详情", notes = "C端商品spu详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "goodsId", value = "商品spuid", required = true),
            @ApiImplicitParam(name = "uid", value = "用户id")
    })
    @GetMapping("/spu")
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult<GoodsDetailVO> getDetailByGoodsId(@RequestParam("goodsId") Long goodsId, @RequestParam("uid") Long uid) {
        logger.info("C端商品spu详情:goodsId=" + goodsId);
        GoodsDetailDTO goodsDetail;
        Object object = redisCache.getCacheObject(GoodsKeyConstant.GOODS_DETAIL_KEY + goodsId);
        if (Objects.nonNull(object)) {
            goodsDetail = (GoodsDetailDTO) object;
        } else {
            goodsDetail = goodsDetailService.getDetailByGoodsId(goodsId);

            if (Objects.nonNull(goodsDetail.getGoodsId())) {
                redisCache.setCacheObject(GoodsKeyConstant.GOODS_DETAIL_KEY + goodsId, goodsDetail);
            }
        }

        if (Objects.isNull(goodsDetail.getGoodsId())) {
            return ResponseResult.success(GoodsEnum.GOODS_HAS_DELETED.getMessage());
        }

        //查询商品spu库存
        List<Long> goodsSkuIds = new ArrayList<>();
        for (SkuDetailDTO goodsSku : goodsDetail.getGoodsSkus()) {
            goodsSkuIds.add(goodsSku.getSkuId());
        }
        int storage = NumberConstant.NUMBER_ZERO.intValue();
        int stockQuantity = NumberConstant.NUMBER_ZERO.intValue();

        Map<Long, GoodsSpuInventoryDTO> skuStockMap = new HashMap<>();
        if (goodsSkuIds.size() > NumberConstant.NUMBER_ZERO.intValue()) {
            //调用库存服务查询库存
            List<GoodsSpuInventoryDTO> goodsSpuInventories = goodsInventoryApi.goodsInventoryBySkuIds(goodsSkuIds);
            for (GoodsSpuInventoryDTO goodsSpuInventory : goodsSpuInventories) {
                storage += goodsSpuInventory.getSaledStorage();
                int stock = goodsSpuInventory.getStockQuantity() + goodsSpuInventory.getPreStorage();
                stockQuantity += stock;

                skuStockMap.put(goodsSpuInventory.getSkuId(), goodsSpuInventory);
            }
        }

        //获取登录人会员等级
        Map<String, Object> userInfoCacheMap = null;
        Integer level = NumberConstant.NUMBER_ZERO.intValue();
        if (getApiUserId() != null && getApiUserId() != NumberConstant.NUMBER_ZERO.intValue()) {
            userInfoCacheMap = redisCache.getCacheMap(GoodsKeyConstant.GOODS_USER_INFO_KEY + getApiUserId());
            if (userInfoCacheMap.size() != NumberConstant.NUMBER_ZERO.intValue()) {
                if (userInfoCacheMap.containsKey("level")) {
                    level = (Integer) JSONObject.fromObject(userInfoCacheMap.get("level")).get("value");
                }
            } else {
                ResponseResult<JmUserReponse> memberReponse = memberService.getMemberByUid(getApiUserId());
                if (memberReponse != null) {
                    JmUserReponse member = memberReponse.getData();
                    if (member != null) {
                        level = member.getLevel().getValue();
                    }
                }
            }
        }
        Integer finalLevel = level;

        logger.info("获取付邮领信息,获取到的用户id为:{},用户等级为:{}", getApiUserId().longValue(), finalLevel);

        // 判断是否开启虚拟销量
        int enableVirtualNum = redisCache.getCacheObject(GoodsKeyConstant.GOODS_VIRTUALNUM_KEY);
        if (enableVirtualNum == NumberConstant.NUMBER_ONE.intValue()) {
            Integer virtualNum = goodsDetail.getVirtualNum();
            if (virtualNum != null) {
                storage += virtualNum;
            }

            goodsDetail.getGoodsSkus().forEach(goodsSkuDTO -> {
                if (skuStockMap.containsKey(goodsSkuDTO.getSkuId())) {
                    GoodsSpuInventoryDTO goodsSpuInventory = skuStockMap.get(goodsSkuDTO.getSkuId());
                    goodsSkuDTO.setSaleStockQuantity(goodsSpuInventory.getStockQuantity() + goodsSpuInventory.getPreStorage());
                    goodsSkuDTO.setSaledStockQuantity(goodsSpuInventory.getSaledStorage() + goodsSkuDTO.getVirtualNum());
                    getSkuMoney(finalLevel, goodsSkuDTO);
                }
            });
        } else {
            goodsDetail.getGoodsSkus().forEach(goodsSkuDTO -> {
                if (skuStockMap.containsKey(goodsSkuDTO.getSkuId())) {
                    GoodsSpuInventoryDTO goodsSpuInventory = skuStockMap.get(goodsSkuDTO.getSkuId());
                    goodsSkuDTO.setSaleStockQuantity(goodsSpuInventory.getStockQuantity() + goodsSpuInventory.getPreStorage());
                    goodsSkuDTO.setSaledStockQuantity(goodsSpuInventory.getSaledStorage());
                    getSkuMoney(finalLevel, goodsSkuDTO);
                }
            });
        }
        goodsDetail.setSaledStockQuantity(storage);
        goodsDetail.setSaleStockQuantity(stockQuantity);

        //sku按商品团购价格升序排序
        goodsDetail.getGoodsSkus().sort((x, y) -> Double.compare(x.getGoodsPrice().doubleValue(), y.getGoodsPrice().doubleValue()));
        SkuDetailDTO goodsSku = goodsDetail.getGoodsSkus().get(NumberConstant.NUMBER_ZERO.intValue());
        GoodsDetailVO goodsDetailVO = convertGoodsDetailDto2Vo(goodsDetail);

        //查询商品的上下架状态
        if (!goodsDetail.getGoodsState().equals(NumberConstant.NUMBER_ONE.intValue())) {
            goodsDetailVO.setGoodsState(Boolean.FALSE);
        } else {
            goodsDetailVO.setGoodsState(Boolean.TRUE);
        }

        //查询商品素材
        if (goodsDetail.getSurceMaterialCount() > NumberConstant.NUMBER_ZERO.intValue()) {
            SourceMaterialDetailVO sourceMaterialDetail = dto2Vo(goodsDetail.getSourceMaterial());
            sourceMaterialDetail.setSurceMaterialCount(goodsDetail.getSurceMaterialCount());
            goodsDetailVO.setSourceMaterial(sourceMaterialDetail);
        }

        //增加评论
        CommentApiOneResponse commentApiOneResponse = null;
        String newOneComment = redisCache.getCacheObject(GoodsKeyConstant.NEWONECOMMENT + goodsId);
        if (StringUtils.isBlank(newOneComment)) {
            try {
                commentApiOneResponse = commentService.commentNewOne(goodsId);
            } catch (Exception ex) {
                logger.warn("remote call commentService warn:" + ex.getMessage());
                redisCache.setCacheObject(GoodsKeyConstant.NEWONECOMMENT + goodsId, "{}", 60, TimeUnit.SECONDS);
            }
        } else {
            if (!"{}".equals(newOneComment)) {
                commentApiOneResponse = (CommentApiOneResponse) JSONObject.toBean(JSONObject.fromObject(newOneComment), CommentApiOneResponse.class);
            }
        }
        goodsDetailVO.setCommentApiOneResponse(commentApiOneResponse);

        //增加redis中的商品浏览量
        processGoodsView(goodsId);

        getSkuActivityMoney(uid, userInfoCacheMap, level, goodsSku, goodsDetailVO);

        SkuDetailDTO goodsSkuMaxByGoodsPrice = goodsDetail.getGoodsSkus().get(goodsDetail.getGoodsSkus().size() - NumberConstant.NUMBER_ONE.intValue());
        goodsDetailVO.setMinGoodsPrice(goodsSku.getGoodsPrice());
        goodsDetailVO.setMaxGoodsPrice(goodsSkuMaxByGoodsPrice.getGoodsPrice());
        goodsDetailVO.setMinGoodsMarketprice(goodsSku.getGoodsMarketprice());
        goodsDetailVO.setMaxGoodsMarketprice(goodsSkuMaxByGoodsPrice.getGoodsMarketprice());


        //查询商品是否是活动商品
        GoodsActivityTypeResponse goodsActivityTypeResponse = gorderActivityServiceClient.activityType(goodsId, getApiUserId().longValue());
        if (goodsActivityTypeResponse != null) {
            if (goodsActivityTypeResponse.getType() != null) {
                GoodsActivityVO goodsActivity = new GoodsActivityVO();

                String purchaseLimitActivity = null;
                Object objectCache = redisCache.getCacheObject(GoodsKeyConstant.PURCHASELIMITACTIVITY + goodsId);
                if (Objects.nonNull(objectCache)) {
                    purchaseLimitActivity = objectCache.toString();
                }

                if (goodsActivityTypeResponse.getType().equals(ActivityTypeEnum.ACTIVITY_FREE_GOODS.getCode())) {
                    //付邮领商品
                    goodsActivity.setActivityType(ActivityTypeEnum.ACTIVITY_FREE_GOODS.getCode());
                    goodsActivity.setActivityName(ActivityTypeEnum.ACTIVITY_FREE_GOODS.getDesc());
                    goodsActivity.setGetNum(goodsActivityTypeResponse.getGetNum());
                    goodsActivity.setLeaveNum(goodsActivityTypeResponse.getLeaveNum());
                    goodsActivity.setQuotaNum(goodsActivityTypeResponse.getQuotaNum());
                    goodsActivity.setIfGet(goodsActivityTypeResponse.getIfGet() == null ? 0 : goodsActivityTypeResponse.getIfGet());
                    goodsActivity.setPurchaseLimitAmount(goodsActivityTypeResponse.getStockSnapshot());
                    if (Objects.isNull(uid)) {
                        goodsDetailVO.getGoodsSkus().forEach(skuDetailVO -> skuDetailVO.setGoodsPrice(BigDecimal.ZERO));
                    }
                } else if (goodsActivityTypeResponse.getType().equals(ActivityTypeEnum.ACTIVITY_TODAY_RECOMMEND.getCode())) {
                    //今日推荐
                    goodsActivity.setActivityType(ActivityTypeEnum.ACTIVITY_TODAY_RECOMMEND.getCode());
                    goodsActivity.setActivityName(ActivityTypeEnum.ACTIVITY_TODAY_RECOMMEND.getDesc());
                    goodsActivity.setActivityStartTime(DateProvider.parseDatetime(goodsActivityTypeResponse.getTodayStartTime()));
                    goodsActivity.setActivityEndTime(DateProvider.parseDatetime(goodsActivityTypeResponse.getTodayEndTime()));

                    if (!StringUtils.isBlank(purchaseLimitActivity)) {
                        goodsActivity.setPurchaseLimitActivity(NumberConstant.NUMBER_ONE.intValue());

                        Object amount = JSONObject.fromObject(objectCache).get("amount");
                        if (Objects.nonNull(amount)) {
                            goodsActivity.setPurchaseLimitAmount((Integer) amount);
                        }
                    }
                } else if (goodsActivityTypeResponse.getType().equals(ActivityTypeEnum.ACTIVITY_TOMORROW_ADVANCE.getCode())) {
                    //明日预告
                    goodsActivity.setActivityType(ActivityTypeEnum.ACTIVITY_TOMORROW_ADVANCE.getCode());
                    goodsActivity.setActivityName(ActivityTypeEnum.ACTIVITY_TOMORROW_ADVANCE.getDesc());
                    goodsActivity.setActivityStartTime(DateProvider.parseDatetime(goodsActivityTypeResponse.getTomorrowStartTime()));
                    goodsActivity.setActivityEndTime(DateProvider.parseDatetime(goodsActivityTypeResponse.getTomorrowEndTime()));

                    if (!StringUtils.isBlank(purchaseLimitActivity)) {
                        goodsActivity.setPurchaseLimitActivity(NumberConstant.NUMBER_ONE.intValue());

                        Object amount = JSONObject.fromObject(objectCache).get("amount");
                        if (Objects.nonNull(amount)) {
                            goodsActivity.setPurchaseLimitAmount((Integer) amount);
                        }
                    }
                }
                goodsDetailVO.setGoodsActivityVO(goodsActivity);
            } else {
                Object obj = redisCache.getCacheObject(GoodsKeyConstant.PURCHASELIMITACTIVITY + goodsId);
                if (Objects.nonNull(obj)) {
                    String purchaseLimitActivity = obj.toString();
                    if (!StringUtils.isBlank(purchaseLimitActivity)) {
                        GoodsActivityVO goodsActivity = new GoodsActivityVO();
                        goodsActivity.setPurchaseLimitActivity(NumberConstant.NUMBER_ONE.intValue());

                        Object amount = JSONObject.fromObject(obj).get("amount");
                        if (Objects.nonNull(amount)) {
                            goodsActivity.setPurchaseLimitAmount((Integer) amount);
                        }
                        goodsDetailVO.setGoodsActivityVO(goodsActivity);
                    }
                }
            }
        }

        //添加足迹和判断商品是否收
        if (getApiUserId() != null && getApiUserId() != NumberConstant.NUMBER_ZERO.intValue()) {
            goodsDetailVO.setFavorites(goodsFavoritesService.isGoodsFavorites(getApiUserId(), goodsId));
            goodsFootprintService.FootprintAdd(getApiUserId().longValue(), goodsId);
        }
        return ResultGenerator.genSuccessResult(goodsDetailVO);
    }

    private void getSkuMoney(Integer finalLevel, SkuDetailDTO goodsSkuDTO) {
        if (finalLevel.equals(Level.manager.getValue())) {
            BigDecimal selfPurchaseMoney = goodsSkuDTO.getGoodsPrice().subtract(goodsSkuDTO.getPlatinumPrice());
            goodsSkuDTO.setSelfPurchaseMoney(selfPurchaseMoney.setScale(NumberConstant.NUMBER_ONE.intValue(), BigDecimal.ROUND_DOWN));
            goodsSkuDTO.setShareMoney(String.valueOf(selfPurchaseMoney.setScale(NumberConstant.NUMBER_ONE.intValue(), BigDecimal.ROUND_DOWN)));
        } else if (finalLevel.equals(Level.goodManager.getValue())) {
            BigDecimal selfPurchaseMoney = goodsSkuDTO.getGoodsPrice().subtract(goodsSkuDTO.getDiamondsPrice());
            goodsSkuDTO.setSelfPurchaseMoney(selfPurchaseMoney.setScale(NumberConstant.NUMBER_ONE.intValue(), BigDecimal.ROUND_DOWN));

            String startMoney = String.valueOf((goodsSkuDTO.getGoodsPrice().subtract(goodsSkuDTO.getDiamondsPrice())).setScale(NumberConstant.NUMBER_ONE.intValue(), BigDecimal.ROUND_DOWN));
            String endMoney = String.valueOf((goodsSkuDTO.getPlatinumPrice().subtract(goodsSkuDTO.getDiamondsPrice())).setScale(NumberConstant.NUMBER_ONE.intValue(), BigDecimal.ROUND_DOWN));
            goodsSkuDTO.setShareMoney(endMoney + "~" + startMoney);
        } else if (finalLevel.equals(Level.gold.getValue())) {
            goodsSkuDTO.setSelfPurchaseMoney((goodsSkuDTO.getGoodsPrice().subtract(goodsSkuDTO.getKingPrice())).setScale(NumberConstant.NUMBER_ONE.intValue(), BigDecimal.ROUND_DOWN));

            String startMoney = String.valueOf((goodsSkuDTO.getGoodsPrice().subtract(goodsSkuDTO.getKingPrice())).setScale(NumberConstant.NUMBER_ONE.intValue(), BigDecimal.ROUND_DOWN));
            String endMoney = String.valueOf((goodsSkuDTO.getDiamondsPrice().subtract(goodsSkuDTO.getKingPrice())).setScale(NumberConstant.NUMBER_ONE.intValue(), BigDecimal.ROUND_DOWN));
            goodsSkuDTO.setShareMoney(endMoney + "~" + startMoney);
        }
    }

    private void processGoodsView(Long goodsId) {
        if (redisTemplate.hasKey(GoodsKeyConstant.GOODS_KEY + goodsId)) {
            redisTemplate.opsForValue().increment(GoodsKeyConstant.GOODS_KEY + goodsId, NumberConstant.NUMBER_ONE.intValue());
        } else {
            redisTemplate.opsForValue().set(GoodsKeyConstant.GOODS_KEY + goodsId, NumberConstant.NUMBER_ONE.intValue());
        }
    }

    /**
     * 根据商品sku id查询商品详情
     *
     * @param goodsSkuId 商品 sku id
     * @return 商品详情
     */
    @ApiOperation(value = "C端商品sku详情", notes = "C端商品sku详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "goodsSkuId", value = "商品skuid", required = true),
            @ApiImplicitParam(name = "uid", value = "用户id")
    })
    @GetMapping("/sku")
    public ResponseResult<GoodsDetailVO> getDetailByGoodsSkuId(@RequestParam("goodsSkuId") Long
                                                                       goodsSkuId, @RequestParam("uid") Long uid) {
        GoodsDetailDTO goodsDetail = goodsDetailService.getDetailByGoodsSkuId(goodsSkuId);

        if (Objects.isNull(goodsDetail.getGoodsId())) {
            return ResponseResult.success(GoodsEnum.GOODS_HAS_DELETED.getMessage());
        }

        //查询商品sku库存
        List<Long> goodsSkuIds = new ArrayList<>();

        for (SkuDetailDTO goodsSku : goodsDetail.getGoodsSkus()) {
            goodsSkuIds.add(goodsSku.getSkuId());
        }
        Integer storage = NumberConstant.NUMBER_ZERO.intValue();
        Integer stockQuantity = NumberConstant.NUMBER_ZERO.intValue();

        Map<Long, GoodsSpuInventoryDTO> skuStockMap = new HashMap<>();
        if (goodsSkuIds.size() > NumberConstant.NUMBER_ZERO.intValue()) {
            //调用库存服务查询库存
            List<GoodsSpuInventoryDTO> goodsSpuInventories = goodsInventoryApi.goodsInventoryBySkuIds(goodsSkuIds);
            for (GoodsSpuInventoryDTO goodsSpuInventory : goodsSpuInventories) {
                storage += goodsSpuInventory.getSaledStorage();
                Integer stock = goodsSpuInventory.getStockQuantity() + goodsSpuInventory.getPreStorage();
                stockQuantity += stock;

                skuStockMap.put(goodsSpuInventory.getSkuId(), goodsSpuInventory);
            }
        }

        //获取登录人会员等级
        Map<String, Object> userInfoCacheMap = null;
        Integer level = NumberConstant.NUMBER_ZERO.intValue();
        if (getApiUserId() != null && getApiUserId() != NumberConstant.NUMBER_ZERO.intValue()) {
            userInfoCacheMap = redisCache.getCacheMap(GoodsKeyConstant.GOODS_USER_INFO_KEY + getApiUserId());
            if (userInfoCacheMap.size() != NumberConstant.NUMBER_ZERO.intValue()) {
                if (userInfoCacheMap.containsKey("level")) {
                    level = (Integer) JSONObject.fromObject(userInfoCacheMap.get("level")).get("value");
                }
            } else {
                ResponseResult<JmUserReponse> memberReponse = memberService.getMemberByUid(getApiUserId());
                if (memberReponse != null) {
                    JmUserReponse member = memberReponse.getData();
                    if (member != null) {
                        level = member.getLevel().getValue();
                    }
                }
            }
        }

        // 判断是否开启虚拟销量
        int enableVirtualNum = redisCache.getCacheObject(GoodsKeyConstant.GOODS_VIRTUALNUM_KEY);
        if (enableVirtualNum == NumberConstant.NUMBER_ONE.intValue()) {
            Integer virtualNum = goodsSkuService.countVirtualNumBySpuId(goodsDetail.getGoodsId());
            if (virtualNum != null) {
                storage += virtualNum;
            }

            goodsDetail.getGoodsSkus().forEach(goodsSkuDTO -> {
                if (skuStockMap.containsKey(goodsSkuDTO.getSkuId())) {
                    GoodsSpuInventoryDTO goodsSpuInventory = skuStockMap.get(goodsSkuDTO.getSkuId());
                    goodsSkuDTO.setSaleStockQuantity(goodsSpuInventory.getStockQuantity() + goodsSpuInventory.getPreStorage());
                    goodsSkuDTO.setSaledStockQuantity(goodsSpuInventory.getSaledStorage() + goodsSkuDTO.getVirtualNum());
                }
            });

        } else {
            goodsDetail.getGoodsSkus().forEach(goodsSkuDTO -> {
                if (skuStockMap.containsKey(goodsSkuDTO.getSkuId())) {
                    GoodsSpuInventoryDTO goodsSpuInventory = skuStockMap.get(goodsSkuDTO.getSkuId());
                    goodsSkuDTO.setSaleStockQuantity(goodsSpuInventory.getStockQuantity() + goodsSpuInventory.getPreStorage());
                    goodsSkuDTO.setSaledStockQuantity(goodsSpuInventory.getSaledStorage());
                }
            });
        }

        goodsDetail.setSaledStockQuantity(storage);
        // goodsDetail.setSaleStockQuantity(stockQuantity);
        //sku按商品团购价格升序排序
        goodsDetail.getGoodsSkus().sort((x, y) -> Double.compare(x.getGoodsPrice().doubleValue(), y.getGoodsPrice().doubleValue()));
        SkuDetailDTO goodsSku = goodsDetail.getGoodsSkus().get(NumberConstant.NUMBER_ZERO.intValue());
        GoodsDetailVO goodsDetailVO = convertGoodsDetailDto2Vo(goodsDetail);

        //查询商品的上下架状态
        if (!goodsDetail.getGoodsState().equals(NumberConstant.NUMBER_ONE.intValue())) {
            goodsDetailVO.setGoodsState(Boolean.FALSE);
        } else {
            goodsDetailVO.setGoodsState(Boolean.TRUE);
        }

        //查询商品素材
        if (goodsDetail.getSurceMaterialCount() > NumberConstant.NUMBER_ZERO.intValue()) {
            SourceMaterialDetailVO sourceMaterialDetail = dto2Vo(goodsDetail.getSourceMaterial());
            sourceMaterialDetail.setSurceMaterialCount(goodsDetail.getSurceMaterialCount());
            goodsDetailVO.setSourceMaterial(sourceMaterialDetail);
        }

        //增加评论
        CommentApiOneResponse commentApiOneResponse = null;
        String newOneComment = redisCache.getCacheObject(GoodsKeyConstant.NEWONECOMMENT + goodsDetail.getGoodsId());
        if (StringUtils.isBlank(newOneComment)) {
            try {
                commentApiOneResponse = commentService.commentNewOne(goodsDetail.getGoodsId());
            } catch (Exception ex) {
                logger.warn("remote call commentService warn:" + ex.getMessage());
                redisCache.setCacheObject(GoodsKeyConstant.NEWONECOMMENT + goodsDetail.getGoodsId(), "{}", 60, TimeUnit.SECONDS);
            }
        } else {
            if (!"{}".equals(newOneComment)) {
                commentApiOneResponse = (CommentApiOneResponse) JSONObject.toBean(JSONObject.fromObject(newOneComment), CommentApiOneResponse.class);
            }
        }

        goodsDetailVO.setCommentApiOneResponse(commentApiOneResponse);

        processGoodsView(goodsDetail.getGoodsId());

        getSkuActivityMoney(uid, userInfoCacheMap, level, goodsSku, goodsDetailVO);

        goodsDetailVO.setMinGoodsPrice(goodsSku.getGoodsPrice());
        goodsDetailVO.setMaxGoodsPrice(goodsSku.getGoodsPrice());
        goodsDetailVO.setMinGoodsMarketprice(goodsSku.getGoodsMarketprice());
        goodsDetailVO.setMaxGoodsMarketprice(goodsSku.getGoodsMarketprice());


        //查询商品是否是活动商品
        GoodsActivityTypeResponse goodsActivityTypeResponse = gorderActivityServiceClient.activityType(goodsDetail.getGoodsId(), getApiUserId().longValue());
        if (goodsActivityTypeResponse != null) {
            if (goodsActivityTypeResponse.getType() != null) {
                GoodsActivityVO goodsActivity = new GoodsActivityVO();
                String purchaseLimitActivity = null;
                if (Objects.nonNull(redisCache.getCacheObject(GoodsKeyConstant.PURCHASELIMITACTIVITY + goodsDetail.getGoodsId()))) {
                    purchaseLimitActivity = redisCache.getCacheObject(GoodsKeyConstant.PURCHASELIMITACTIVITY + goodsDetail.getGoodsId()).toString();
                }
                if (goodsActivityTypeResponse.getType().equals(ActivityTypeEnum.ACTIVITY_FREE_GOODS.getCode())) {
                    //付邮领商品
                    goodsActivity.setActivityType(ActivityTypeEnum.ACTIVITY_FREE_GOODS.getCode());
                    goodsActivity.setActivityName(ActivityTypeEnum.ACTIVITY_FREE_GOODS.getDesc());
                    goodsActivity.setGetNum(goodsActivityTypeResponse.getGetNum());
                    goodsActivity.setLeaveNum(goodsActivityTypeResponse.getLeaveNum());
                    goodsActivity.setQuotaNum(goodsActivityTypeResponse.getQuotaNum());
                    goodsActivity.setIfGet(goodsActivityTypeResponse.getIfGet() == null ? 0 : goodsActivityTypeResponse.getIfGet());
                    if (Objects.isNull(uid)) {
                        goodsDetailVO.getGoodsSkus().forEach(skuDetailVO -> skuDetailVO.setGoodsPrice(BigDecimal.ZERO));
                    }
                    goodsDetailVO.setSaleStockQuantity(goodsActivityTypeResponse.getStockSnapshot());
                } else if (goodsActivityTypeResponse.getType().equals(ActivityTypeEnum.ACTIVITY_TODAY_RECOMMEND.getCode())) {
                    //今日推荐
                    goodsActivity.setActivityType(ActivityTypeEnum.ACTIVITY_TODAY_RECOMMEND.getCode());
                    goodsActivity.setActivityName(ActivityTypeEnum.ACTIVITY_TODAY_RECOMMEND.getDesc());
                    goodsActivity.setActivityStartTime(DateProvider.parseDatetime(goodsActivityTypeResponse.getTodayStartTime()));
                    goodsActivity.setActivityEndTime(DateProvider.parseDatetime(goodsActivityTypeResponse.getTodayEndTime()));

                    if (!StringUtils.isBlank(purchaseLimitActivity)) {
                        goodsActivity.setPurchaseLimitActivity(NumberConstant.NUMBER_ONE.intValue());

                        Object amount = JSONObject.fromObject(purchaseLimitActivity).get("amount");
                        if (Objects.nonNull(amount)) {
                            goodsActivity.setPurchaseLimitAmount((Integer) amount);
                        }
                    }
                } else if (goodsActivityTypeResponse.getType().equals(ActivityTypeEnum.ACTIVITY_TOMORROW_ADVANCE.getCode())) {
                    //明日预告
                    goodsActivity.setActivityType(ActivityTypeEnum.ACTIVITY_TOMORROW_ADVANCE.getCode());
                    goodsActivity.setActivityName(ActivityTypeEnum.ACTIVITY_TOMORROW_ADVANCE.getDesc());
                    goodsActivity.setActivityStartTime(DateProvider.parseDatetime(goodsActivityTypeResponse.getTomorrowStartTime()));
                    goodsActivity.setActivityEndTime(DateProvider.parseDatetime(goodsActivityTypeResponse.getTomorrowEndTime()));

                    if (!StringUtils.isBlank(purchaseLimitActivity)) {
                        goodsActivity.setPurchaseLimitActivity(NumberConstant.NUMBER_ONE.intValue());

                        Object amount = JSONObject.fromObject(purchaseLimitActivity).get("amount");
                        if (Objects.nonNull(amount)) {
                            goodsActivity.setPurchaseLimitAmount((Integer) amount);
                        }
                    }
                }
                goodsDetailVO.setGoodsActivityVO(goodsActivity);
            } else {
                if (Objects.nonNull(redisCache.getCacheObject(GoodsKeyConstant.PURCHASELIMITACTIVITY + goodsDetail.getGoodsId()))) {
                    String purchaseLimitActivity = redisCache.getCacheObject(GoodsKeyConstant.PURCHASELIMITACTIVITY + goodsDetail.getGoodsId()).toString();
                    if (!StringUtils.isBlank(purchaseLimitActivity)) {
                        GoodsActivityVO goodsActivity = new GoodsActivityVO();
                        goodsActivity.setPurchaseLimitActivity(NumberConstant.NUMBER_ONE.intValue());

                        Object amount = JSONObject.fromObject(purchaseLimitActivity).get("amount");
                        if (Objects.nonNull(amount)) {
                            goodsActivity.setPurchaseLimitAmount((Integer) amount);
                        }
                        goodsDetailVO.setGoodsActivityVO(goodsActivity);
                    }
                }
            }
        }
        //添加足迹
        if (getApiUserId() != null && getApiUserId() != NumberConstant.NUMBER_ZERO.intValue()) {
            goodsDetailVO.setFavorites(goodsFavoritesService.isGoodsFavorites(getApiUserId(), goodsDetail.getGoodsId()));
            goodsFootprintService.FootprintAdd(getApiUserId().longValue(), goodsDetail.getGoodsId());
        }
        return ResultGenerator.genSuccessResult(goodsDetailVO);
    }

    private void getSkuActivityMoney(@RequestParam("uid") Long uid, Map<String, Object> userInfoCacheMap, Integer level, SkuDetailDTO goodsSku, GoodsDetailVO goodsDetailVO) {
        if (level.equals(Level.manager.getValue())) {
            BigDecimal selfPurchaseMoney = goodsSku.getGoodsPrice().subtract(goodsSku.getPlatinumPrice());
            goodsDetailVO.setSelfPurchaseMoney(selfPurchaseMoney.setScale(NumberConstant.NUMBER_ONE.intValue(), BigDecimal.ROUND_DOWN));
            goodsDetailVO.setShareMoney(String.valueOf(selfPurchaseMoney.setScale(NumberConstant.NUMBER_ONE.intValue(), BigDecimal.ROUND_DOWN)));
        } else if (level.equals(Level.goodManager.getValue())) {
            BigDecimal selfPurchaseMoney = goodsSku.getGoodsPrice().subtract(goodsSku.getDiamondsPrice());
            goodsDetailVO.setSelfPurchaseMoney(selfPurchaseMoney.setScale(NumberConstant.NUMBER_ONE.intValue(), BigDecimal.ROUND_DOWN));

            String startMoney = String.valueOf((goodsSku.getGoodsPrice().subtract(goodsSku.getDiamondsPrice())).setScale(NumberConstant.NUMBER_ONE.intValue(), BigDecimal.ROUND_DOWN));
            String endMoney = String.valueOf((goodsSku.getPlatinumPrice().subtract(goodsSku.getDiamondsPrice())).setScale(NumberConstant.NUMBER_ONE.intValue(), BigDecimal.ROUND_DOWN));
            goodsDetailVO.setShareMoney(endMoney + "~" + startMoney);
        } else if (level.equals(Level.gold.getValue())) {
            goodsDetailVO.setSelfPurchaseMoney((goodsSku.getGoodsPrice().subtract(goodsSku.getKingPrice())).setScale(NumberConstant.NUMBER_ONE.intValue(), BigDecimal.ROUND_DOWN));

            String startMoney = String.valueOf((goodsSku.getGoodsPrice().subtract(goodsSku.getKingPrice())).setScale(NumberConstant.NUMBER_ONE.intValue(), BigDecimal.ROUND_DOWN));
            String endMoney = String.valueOf((goodsSku.getDiamondsPrice().subtract(goodsSku.getKingPrice())).setScale(NumberConstant.NUMBER_ONE.intValue(), BigDecimal.ROUND_DOWN));
            goodsDetailVO.setShareMoney(endMoney + "~" + startMoney);
        }

        if (uid != null) {
            if (getApiUserId() != null && getApiUserId() != NumberConstant.NUMBER_ZERO.intValue()) {
                if (!uid.equals(getApiUserId().longValue())) {
                    userInfoCacheMap = redisCache.getCacheMap(GoodsKeyConstant.GOODS_USER_INFO_KEY + uid);
                }
            } else {
                userInfoCacheMap = redisCache.getCacheMap(GoodsKeyConstant.GOODS_USER_INFO_KEY + uid);
            }
            MemberVO memberVO = new MemberVO();
            memberVO.setUid(uid);
            if (userInfoCacheMap != null && userInfoCacheMap.size() > NumberConstant.NUMBER_ZERO.intValue()) {
                if (userInfoCacheMap.containsKey("name")) {
                    Object nameObject = userInfoCacheMap.get("name");
                    if (Objects.nonNull(nameObject)) {
                        memberVO.setName(String.valueOf(nameObject));
                    }
                }
                if (userInfoCacheMap.containsKey("avatar")) {
                    Object avatarObject = userInfoCacheMap.get("avatar");
                    if (Objects.nonNull(avatarObject)) {
                        memberVO.setAvatar(String.valueOf(avatarObject));
                    }
                }
                if (userInfoCacheMap.containsKey("certificate")) {
                    Object certificateObject = userInfoCacheMap.get("certificate");
                    if (Objects.nonNull(certificateObject)) {
                        memberVO.setCertificate(String.valueOf(certificateObject));
                    }
                }
                if (userInfoCacheMap.containsKey("qr_weixin_img")) {
                    Object personalQrObject = userInfoCacheMap.get("qr_weixin_img");
                    if (Objects.nonNull(personalQrObject)) {
                        memberVO.setPersonalQr(String.valueOf(personalQrObject));
                    }
                }
            } else {
                ResponseResult<JmUserReponse> memberReponse = memberService.getMemberByUid(uid.intValue());
                if (memberReponse != null) {
                    JmUserReponse jmUserReponse = memberReponse.getData();
                    if (jmUserReponse != null) {
                        memberVO.setName(jmUserReponse.getName());
                        memberVO.setAvatar(jmUserReponse.getAvatar());
                        memberVO.setCertificate(jmUserReponse.getCertificate());
                        memberVO.setPersonalQr(jmUserReponse.getQrweixinimg());
                    }
                }
            }
            goodsDetailVO.setMember(memberVO);
        }
    }

    /**
     * C端接口-商品搜索-热门搜索标签
     *
     * @return 热门搜索标签集合
     */
    @GetMapping("/goodsHotSearchLabel")
    @ApiOperation(value = "C端接口-商品搜索-热门搜索标签", notes = "C端接口-商品搜索-热门搜索标签")
    public ResponseResult<List<String>> getGoodsHotSearchLabel() {
        List<String> labelList = Arrays.asList(goodsHotSearchLabel.split(","));
        return ResultGenerator.genSuccessResult(labelList);
    }

    /**
     * 根据商品sku id查询库存
     *
     * @param skuId 商品sku id
     * @return 库存
     */
    @GetMapping("/inventory/{skuId}")
    public ResponseResult<Integer> getInventoryBySkuId(@PathVariable("skuId") Long skuId) {
        //查询商品sku库存
        List<Long> goodsSkuIds = new ArrayList<>();
        goodsSkuIds.add(skuId);
        List<GoodsSpuInventoryDTO> goodsSpuInventories =
                goodsInventoryApi.goodsInventoryBySkuIds(goodsSkuIds);

        Integer storage = NumberConstant.NUMBER_ZERO.intValue();
        for (GoodsSpuInventoryDTO goodsSpuInventory : goodsSpuInventories) {
            storage += goodsSpuInventory.getStockQuantity();
        }
        return ResultGenerator.genSuccessResult(storage);
    }

    /**
     * 根据商品spu id查询商品详情(海报接口使用)
     *
     * @param goodsId 商品 spu id
     * @return 商品详情
     */
    @GetMapping("/api/poster/{goodsId}")
    @ApiOperation(value = "C端商品SPU海报详情", notes = "C端商品SPU海报详情")
    @ApiImplicitParam(name = "goodsId", value = "商品SPU ID")
    public ResponseResult<GoodsPosterDetailVO> getPosterDetailByGoodsId(@PathVariable("goodsId") Long goodsId) {
        GoodsDTO goodsDetail = goodsService.getGoodsDetailById(goodsId);
        GoodsPosterDetailVO goodsPosterDetail = new GoodsPosterDetailVO();

        goodsPosterDetail.setGoodsId(goodsId);
        goodsPosterDetail.setGoodsName(goodsDetail.getGoodsName());
        goodsPosterDetail.setGoodsImage(ImageResizeUtil.imageResize(goodsDetail.getGoodsImage(), ImageResizeEnum.POSTER_GOODS));

        Object cacheObject = redisCache.getCacheObject(GoodsKeyConstant.POSTAGEGOODS + goodsId);
        if (!Objects.isNull(cacheObject)) {
            goodsPosterDetail.setGoodsPrice(BigDecimal.ZERO);
        } else {
            goodsPosterDetail.setGoodsPrice(goodsDetail.getGoodsPrice());
        }

        goodsPosterDetail.setGoodsMarketprice(goodsDetail.getGoodsMarketprice());

        if (getApiUserId() != null && getApiUserId() != NumberConstant.NUMBER_ZERO.intValue()) {
            ResponseResult<JmUserReponse> memberReponse = memberService.getMemberByUid(getApiUserId());
            if (memberReponse != null) {
                JmUserReponse member = memberReponse.getData();
                if (member != null) {
                    goodsPosterDetail.setNickname(member.getName());
                    goodsPosterDetail.setAvatar(ImageResizeUtil.imageResize(member.getAvatar(), ImageResizeEnum.POSTER_HEADER));
                }
            }
        }

        GoodsActivityTypeResponse goodsActivityTypeResponse = gorderActivityServiceClient.activityType(goodsId, getApiUserId().longValue());
        if (goodsActivityTypeResponse != null) {
            if (goodsActivityTypeResponse.getType() != null) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
                if (goodsActivityTypeResponse.getType().equals(ActivityTypeEnum.ACTIVITY_FREE_GOODS.getCode())) {
                    //付邮领商品
                    goodsPosterDetail.setIsGroupPurchase(NumberConstant.NUMBER_ZERO.intValue());
                } else if (goodsActivityTypeResponse.getType().equals(ActivityTypeEnum.ACTIVITY_TODAY_RECOMMEND.getCode())) {
                    //今日推荐
                    goodsPosterDetail.setIsGroupPurchase(NumberConstant.NUMBER_ONE.intValue());
                    goodsPosterDetail.setGroupPurchaseBeginTime(simpleDateFormat.format(DateProvider.parseDatetime(goodsActivityTypeResponse.getTodayStartTime())));
                    goodsPosterDetail.setGroupPurchaseEndTime(simpleDateFormat.format(DateProvider.parseDatetime(goodsActivityTypeResponse.getTodayEndTime())));
                } else if (goodsActivityTypeResponse.getType().equals(ActivityTypeEnum.ACTIVITY_TOMORROW_ADVANCE.getCode())) {
                    //明日预告
                    goodsPosterDetail.setIsGroupPurchase(NumberConstant.NUMBER_ONE.intValue());
                    goodsPosterDetail.setGroupPurchaseBeginTime(simpleDateFormat.format(DateProvider.parseDatetime(goodsActivityTypeResponse.getTomorrowStartTime())));
                    goodsPosterDetail.setGroupPurchaseEndTime(simpleDateFormat.format(DateProvider.parseDatetime(goodsActivityTypeResponse.getTomorrowEndTime())));
                }
            }
        } else {
            goodsPosterDetail.setIsGroupPurchase(NumberConstant.NUMBER_ZERO.intValue());
        }
        return ResultGenerator.genSuccessResult(goodsPosterDetail);
    }

    /**
     * 将商品详情DTO对象转换为VO对象
     *
     * @param goodsDetail 商品详情DTO
     * @return GoodsDetailVO 商品详情VO
     */
    private GoodsDetailVO convertGoodsDetailDto2Vo(GoodsDetailDTO goodsDetail) {
        GoodsDetailVO targetGoods = null;
        try {
            targetGoods = goodsDetail.clone(GoodsDetailVO.class, CloneDirection.OPPOSITE);
        } catch (Exception e) {
            ExceptionEnum.FAIL_CHANGE.newException();
        }
        return targetGoods;
    }

    /**
     * 将商品spu DTO对象集合转换为VO对象集合
     *
     * @param goods DTO集合
     * @return List<GoodsVO> VO对象集合
     */
    private List<GoodsVO> convertGoodsDtoList2VoList(List<GoodsDTO> goods) {
        List<GoodsVO> targetGoods = null;
        try {
            targetGoods = ObjectUtils.convertList(goods, GoodsVO.class);
        } catch (Exception e) {
            ExceptionEnum.FAIL_CHANGE.newException();
        }
        return targetGoods;
    }


    /**
     * dto->vo
     *
     * @param dto
     * @return
     */
    private SourceMaterialDetailVO dto2Vo(SourceMaterialDetailDTO dto) {
        SourceMaterialDetailVO vo = null;
        try {
            vo = dto.clone(SourceMaterialDetailVO.class);
        } catch (Exception e) {
            ExceptionEnum.FAIL_CHANGE.newException();
        }
        return vo;
    }
}
